package ruifight.member.wxController;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.imageio.ImageIO;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.util.Base64Utils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import ruifight.member.model.ShopInfoWithBLOBs;
import ruifight.member.model.security.MyUserDetail;
import ruifight.member.service.ShopInfoService;
import ruifight.member.util.CommonUtil;
import ruifight.member.util.HttpClientUtil;
import ruifight.member.util.JsonUtils;


@Controller
@RequestMapping("interface/wx/code")
public class CodeController {

	private static final Logger logger = LoggerFactory.getLogger(CodeController.class);
	
	@Resource
	private ShopInfoService shopInfoService;
	
	/**
	 * 获取店铺二维码
	 * @return
	 */
	@RequestMapping("/getCode")
	@ResponseBody
	public Map<String, Object> getCode() {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
			ShopInfoWithBLOBs shopInfo=shopInfoService.selectByPrimaryKey(ud.getShopInfoId());
			if(StringUtils.isEmpty(shopInfo.getWxCode())) {
				String getTokenUrl=CommonUtil.getPropertiesParam("getTokenUrl");
				Map<String,String> getTokenParamMap=new HashMap<String,String>();
				getTokenParamMap.put("grant_type", CommonUtil.getPropertiesParam("grant_type"));
				getTokenParamMap.put("appid", CommonUtil.getPropertiesParam("appid"));
				getTokenParamMap.put("secret", CommonUtil.getPropertiesParam("secret"));
				String getTokenJson=HttpClientUtil.doGet(getTokenUrl, getTokenParamMap);
				String access_token=JsonUtils.fromJson(getTokenJson).get("access_token").asText();
				//获取二维码
				String getCodeUnLimitUrl=CommonUtil.getPropertiesParam("getCodeUnLimitUrl");
				Map<String,String> getCodeUnLimitMap=new HashMap<String,String>();
				getCodeUnLimitMap.put("scene", shopInfo.getShopCode());
				getCodeUnLimitMap.put("page", CommonUtil.getPropertiesParam("codeUnLimitPage"));
				byte[] codeUnLimitBytes=HttpClientUtil.doInputStreamPostJson(getCodeUnLimitUrl+"?access_token="+access_token, JsonUtils.toJson(getCodeUnLimitMap));
				if(codeUnLimitBytes==null){
					map.put("errcode", -1);
					return map;
				}
				File tempFile = File.createTempFile("temp", ".png");
				BufferedOutputStream bos = null;  
				ByteArrayOutputStream baos = null;
			    FileOutputStream fos = null;  
				try{
					fos = new FileOutputStream(tempFile); 
					bos = new BufferedOutputStream(fos);  
					baos= new ByteArrayOutputStream();
		            bos.write(codeUnLimitBytes);
		            bos.flush();
					codeAddTitle(tempFile, baos, shopInfo.getShopName());
					shopInfo.setWxCode(Base64Utils.encodeToString(baos.toByteArray()));
				}catch(Exception e){
					logger.error("二维码添加标题失败", e);
				}finally {  
		            if (bos != null) {  
		                try {  
		                    bos.close();  
		                } catch (IOException e) {  
		                    e.printStackTrace();  
		                }  
		            }  
		            if (baos != null) {  
		                try {  
		                	baos.close();  
		                } catch (IOException e) {  
		                    e.printStackTrace();  
		                }  
		            }  
		            if (fos != null) {  
		                try {  
		                    fos.close();  
		                } catch (IOException e) {  
		                    e.printStackTrace();  
		                }  
		            }  
		        } 
				tempFile.delete();
				shopInfoService.updateByPrimaryKeySelective(shopInfo);
			}
			map.put("errcode", 0);
			map.put("code", shopInfo.getWxCode());
			map.put("shopInfoId", shopInfo.getShopInfoId());
			map.put("shopName", shopInfo.getShopName());
		}catch (Exception e){
			map.put("errcode", -1);
			logger.error("获取店铺二维码失败", e);
		}
		return map;
	}

	private void codeAddTitle(File file,OutputStream os,String title){
        try {
        	BufferedImage  image = ImageIO.read(file);
        	int width = image.getWidth();
        	int height = image.getHeight();
            BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2 = bi.createGraphics();
            g2.setBackground(Color.WHITE);
            g2.clearRect(0, 0, width, height);
            g2.drawImage(image, 0, 40, width - 40, height - 40, null); //这里减去25是为了防止字和图重合
            /** 设置生成图片的文字样式 * */
            Font font = new Font("黑体", Font.BOLD, 30);
            g2.setFont(font);
            g2.setPaint(Color.BLACK);

            /** 设置字体在图片中的位置 在这里是居中* */
            FontRenderContext context = g2.getFontRenderContext();
            Rectangle2D bounds = font.getStringBounds(title, context);
            double x = (width - bounds.getWidth()) / 2;
            //double y = (height - bounds.getHeight()) / 2; //Y轴居中
            double y = 0;
            double ascent = -bounds.getY();
            double baseY = y + ascent+5;

            /** 防止生成的文字带有锯齿 * */
            g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

            /** 在图片上生成文字 * */
            g2.drawString(title, (int) x, (int) baseY);

            ImageIO.write(bi, "jpg", os);
        } catch (IOException e) {
            e.printStackTrace();
        } 
    }
}
